import axios from 'axios'
import { ElMessage,ElNotification } from 'element-plus'
const service = axios.create({
    baseURL: "/api",
    timeout: 2400 * 1000,  //请求超时时间
})

//请求拦截器
service.interceptors.request.use(config => {
    //例如携带token
    config.headers['content-type'] = 'application/json';
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem("token") == null ? '' : 'Bearer ' + localStorage.getItem("token");
    return config;
})
//响应拦截器
service.interceptors.response.use(
    (response: any) => {
        // 未设置状态码则默认成功状态
        const code = response.data.code || 200;
        // 获取错误信息
        const msg =  response.data.message || '未知错误'
        if (code === 500) {
            ElMessage({ message: msg, type: 'error' })
            return Promise.reject(new Error(msg))
        } else if (code === 601) {
            ElMessage({ message: msg, type: 'warning' })
            return Promise.reject('error')
        } else if (code !== 200) {
            ElNotification.error({ title: msg })
            return Promise.reject('error')
        } else {
            return response.data
        }
    },
    error => {
        console.log('err' + error) // for debug
        if (error.response.status == 403) {
            ElMessage.error('错了')
        } else {
            ElMessage.error('服务器请求错误，请稍后再试')
        }
        return Promise.reject(error)
    }
)
export default service;